package com.ms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.dao.GameMapper;
import com.ms.dao.OrganizerMapper;
import com.ms.dao.RegistrationMapper;
import com.ms.entity.*;
import com.ms.dao.EventMapper;
import com.ms.dao.ScoreMapper;
import com.ms.service.inter.OrganizerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrganizerServiceImpl extends ServiceImpl<OrganizerMapper, Organizer> implements OrganizerService {

    @Autowired
    private OrganizerMapper organizerMapper;
    
    @Autowired
    private RegistrationMapper registrationMapper;
    
    @Autowired
    private GameMapper gameMapper;
    
    @Autowired
    private EventMapper eventMapper;
    
    @Autowired
    private ScoreMapper scoreMapper;

    @Override
    public boolean register(Organizer organizer) {
        // 检查账号是否已存在
        Organizer existingOrganizer = organizerMapper.selectByAccount(organizer.getOrAccount());
        if (existingOrganizer != null) {
            return false; // 账号已存在，注册失败
        }

        // 设置默认值
        organizer.setOrIsUsing(1); // 默认启用

        // 插入新用户
        int result = organizerMapper.insert(organizer);
        return result > 0;
    }

    @Override
    public Organizer loginByAccount(String account, String password) {
        Organizer organizer = organizerMapper.selectByAccountAndPassword(account, password);
        // 检查账号是否启用
        if (organizer != null && organizer.getOrIsUsing() == 1) {
            return organizer;
        }
        return null;
    }

    @Override
    public boolean updatePassword(String account, String oldPassword, String newPassword) {
        // 先验证原密码是否正确
        Organizer organizer = organizerMapper.selectByAccountAndPassword(account, oldPassword);
        if (organizer == null) {
            return false; // 原密码错误
        }

        // 更新密码
        int result = organizerMapper.updatePassword(account, newPassword);
        return result > 0;
    }

    @Override
    public boolean retrievePassword(String account, String contact, String newPassword) {
        // 验证账号和联系方式是否匹配
        QueryWrapper<Organizer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("or_account", account).eq("or_contact", contact);
        Organizer organizer = organizerMapper.selectOne(queryWrapper);

        if (organizer == null) {
            return false; // 账号或联系方式不匹配
        }

        // 更新密码
        int result = organizerMapper.updatePassword(account, newPassword);
        return result > 0;
    }

    // 在类中添加以下方法实现
    @Override
    public boolean updateOrganizerInfo(Organizer organizer) {
        // 只更新指定字段，不更新密码、创建时间、启用状态等敏感字段
        return this.updateById(organizer);
    }
    
    /**
     * 获取所有主办方
     * @return 主办方列表
     */
    @Override
    public List<Organizer> findAll() {
        try {
            // 使用MyBatis-Plus的查询方法
            return this.baseMapper.selectList(null);
        } catch (Exception e) {
            throw new RuntimeException("获取所有主办方失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 审批通过用户报名申请，并增加对应项目对象的当前人数
     * @param regId 报名ID
     * @return 是否操作成功
     */
    public boolean approveRegistration(Integer regId) {
        // 获取报名信息
        Registration registration = registrationMapper.selectById(regId);
        if (registration == null) {
            return false; // 报名信息不存在
        }
        
        // 获取对应的项目
        Event event = eventMapper.selectById(registration.getEventID());
        if (event == null) {
            return false; // 项目不存在
        }
        
        // 检查是否达到最大人数限制
        if (event.getMaxParticipants() != null && 
            event.getCurrentParticipants() != null && 
            event.getCurrentParticipants() >= event.getMaxParticipants()) {
            return false; // 已达到最大人数限制
        }
        
        // 更新报名状态为通过（假设1表示通过）
        registration.setIsUsing(1);
        int result = registrationMapper.updateById(registration);
        
        if (result > 0) {
            // 增加当前报名人数
            if (event.getCurrentParticipants() == null) {
                event.setCurrentParticipants(1);
            } else {
                event.setCurrentParticipants(event.getCurrentParticipants() + 1);
            }
            // 更新项目
            eventMapper.updateById(event);
            return true;
        }
        
        return false;
    }
    
    /**
     * 删除报名信息，如果删除的是已通过审批的报名信息，则项目参赛人数减一
     * @param regId 报名ID
     * @return 是否操作成功
     */
    public boolean deleteRegistration(Integer regId) {
        // 获取报名信息
        Registration registration = registrationMapper.selectById(regId);
        if (registration == null) {
            return false; // 报名信息不存在
        }
        
        // 判断是否是已通过审批的报名信息
        boolean approved = registration.getIsUsing() != null && registration.getIsUsing() == 1;
        
        // 删除报名信息
        int result = registrationMapper.deleteById(regId);
        
        // 如果删除成功且是已通过审批的报名信息，则需要减少项目参赛人数
        if (result > 0 && approved) {
            // 获取对应的项目
            Event event = eventMapper.selectById(registration.getEventID());
            if (event != null && event.getCurrentParticipants() != null && event.getCurrentParticipants() > 0) {
                // 减少当前报名人数
                event.setCurrentParticipants(event.getCurrentParticipants() - 1);
                // 更新项目
                eventMapper.updateById(event);
            }
            
            // 根据比赛gameid和项目eventid和userid和轮次默认为1，删除对应的成绩单score数据
            QueryWrapper<Score> scoreQueryWrapper = new QueryWrapper<>();
            scoreQueryWrapper.eq("game_id", registration.getGameID())
                    .eq("event_id", registration.getEventID())
                    .eq("user_id", registration.getUserID())
                    .eq("rank_id", 1); // 轮次默认为1
            scoreMapper.delete(scoreQueryWrapper);
            
            return true;
        }
        
        return result > 0;
    }
}